// import块
var fs = require('fs');
var request = require('request');

// 参数定义块
// 日志文件请求接口
var requestUrl = "http://applog.szjs.gov.cn/elasticsearch/_msearch";
// 日志被保存的时使用的文件名
var fileName = "zghc.log";
// 查询开始时间
var beginTime = new Date("2021/01/07 09:00:00");
// 查询结束时间
var endTime = new Date();
// 主机名称
var beatHoustName1 =  "zghc1";
// 主机名称
var beatHoustName2 =  "zghc1";
// 系统中日志文件路径
var source = "/home/weblogic/log/zghc1.log"
// 日志总条数，平台限制，最大不超过10000条
var pageSize = 9999;


// 查询条件配置
// 查询index配置
var indexConfig = {
    "index": "applog-*",
    "ignore_unavailable": true,
    "timeout": 30000000,
    "preference": 1600765917567
};
var queryConfig = {
    "version": true,
    "size": pageSize,
    "sort": [{
        "@timestamp": {
            "order": "asc",
            "unmapped_type": "boolean"
        }
    }],
    "_source": {
        "excludes": []
    },
    "aggs": {
        "2": {
            "date_histogram": {
                "field": "@timestamp",
                "interval": "5s",
                "time_zone": "Asia/Shanghai",
                "min_doc_count": 1
            }
        }
    },
    "stored_fields": ["*"],
    "script_fields": {},
    "docvalue_fields": [{ "field": "@timestamp", "format": "date_time" }],
    "query": {
        "bool": {
            "must": [{
                "match_all": {}
            }, {
                "match_phrase": {
                    "source": {

                        "query": source
                    }
                }
            }, {
                "bool": {
                    "should": [{
                        "match_phrase": {
                            "beat.hostname": beatHoustName1
                        }
                    }, {
                        "match_phrase": {
                            "beat.hostname": beatHoustName2
                        }
                    }],
                    "minimum_should_match": 1
                }
            }, {
                "range": {
                    "@timestamp": {
                        "gte": beginTime == null ? 1600765586489 : beginTime.getTime(),
                        "lte": endTime == null ? 1600765935934 : endTime.getTime(),
                        "format": "epoch_millis"
                    }
                }
            }],
            "filter": [],
            "should": [],
            "must_not": []
        }
    },
    "highlight": {
        "pre_tags": ["@kibana-highlighted-field@"],
        "post_tags": ["@/kibana-highlighted-field@"],
        "fields": {
            "*": {}
        },
        "fragment_size": 2147483647
    }
}

// 组装查询
var requestData = JSON.stringify(indexConfig) + "\n" + JSON.stringify(queryConfig) + "\n";

// 数据请求块
request({
    url: requestUrl,
    method: "POST",
    headers: {
        "content-type": "application/x-ndjson",
        "kbn-version": "6.4.2"
    },
    body: requestData
}, function (error, response, body) {
    if (!error && response.statusCode == 200) {
        var log = "";
        var respData = JSON.parse(body);
        var hits = respData && respData.responses && respData.responses[0] && respData.responses[0].hits && respData.responses[0].hits.hits;
        if (hits instanceof Array) {
            for (var i = 0; i < hits.length; i++) {
                var item = hits[i];
                log += ("\n" + item._source.message);
            }
        }
        // console.log(log);
        fs.writeFile(fileName, log, { flag: 'w', encoding: 'utf-8', mode: '0666' }, function (error) {
            if (error) {
                console.log("文件写入失败")
                console.log(error);
            } else {
                console.log("文件写入成功");
            }
        });
    }
});
